using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

namespace CGF
{
    public class UISortingComponent : ComponentBase, IAwake<GameObject>
    {
        private GameObject gameObject;
        private int layerIndex = 0;
        private Transform rootCanvasNode = null;
        private RectTransform currPanelRoot = null;

        public void Awake(GameObject gameObject)
        {
            this.gameObject = gameObject;
            gameObject.AddDestroyEvent(OnGameObjectDestroy);
            currPanelRoot = gameObject.transform as RectTransform;
            rootCanvasNode = currPanelRoot.parent;

            while (rootCanvasNode && !UISortingManager.IsRootCanvasNode(rootCanvasNode))
            {
                currPanelRoot = rootCanvasNode as RectTransform;
                rootCanvasNode = rootCanvasNode.parent as RectTransform;
            }

            if (currPanelRoot.parent != rootCanvasNode)
            {
                LogError($"{gameObject.name} 不是UI根节点，不能绑定 UISortingComponentView 组件");
                return;
            }

            if (!UISortingManager.allComponents.Contains(this)) UISortingManager.allComponents.Add(this);

            RefreshSorting();

            RefreshOtherUI();
        }

        private async void RefreshOtherUI()
        {
            await CTask.Wait(0.1f);
            if (!Application.isPlaying) return;
            for (int i = 0; i < UISortingManager.allComponents.Count; i++)
            {
                UISortingComponent component = UISortingManager.allComponents[i];
                if (component != this && component.gameObject.activeSelf)
                {
                    component.RefreshSorting();
                }
            }
        }

        //刷新层级，在UI显示之后或动态添加特效时调用
        public void RefreshSorting()
        {
            if (rootCanvasNode && currPanelRoot)
            {
                //判断当前是第几个节点
                layerIndex = 0;
                for (int i = 0; i < rootCanvasNode.childCount; i++)
                {
                    Transform child = rootCanvasNode.GetChild(i);
                    if (!child.gameObject.activeSelf || !child.GetComponent<MonoLifeListener>().enabled)
                    {
                        continue;
                    }
                    if (child == currPanelRoot)
                    {
                        break;
                    }
                    layerIndex++;
                }

                Canvas rootCanvasNodeCanvas = rootCanvasNode.GetComponent<Canvas>();
                //根UI层级起步，每个预置体跳跃1000，预置体内部每个画布或特效加上这个基础值
                int prefabRootOrder = rootCanvasNodeCanvas.sortingOrder + (layerIndex * UISortingManager.LayerJump);

                //预置体根节点确保有一个画布，否则子节点的层级无效
                Canvas currPanelRootCanvas = currPanelRoot.GetComponent<Canvas>();
                if (!currPanelRootCanvas) currPanelRootCanvas = currPanelRoot.gameObject.AddComponent<Canvas>();
                currPanelRootCanvas.overrideSorting = true;
                currPanelRootCanvas.sortingLayerName = rootCanvasNodeCanvas.sortingLayerName;
                currPanelRootCanvas.sortingOrder = prefabRootOrder;
                GraphicRaycaster raycaster = currPanelRoot.GetComponent<GraphicRaycaster>();
                if (!raycaster) currPanelRoot.gameObject.AddComponent<GraphicRaycaster>();

                //子节点的画布和特效累加根节点的值
                prefabRootOrder++;
                UISortingManager.SetChildrenSortingOrder(currPanelRoot, rootCanvasNodeCanvas.sortingLayerName, prefabRootOrder);
            }
        }

        /// <summary>
        /// 刷新特定Transform的UI层级
        /// </summary>
        public void RefreshTransformSorting(Transform transform)
        {
            Transform parent = transform;
            while (!parent.parent.GetComponent<CanvasScaler>())
            {
                parent = parent.parent;
            }
            Canvas canvas = parent.GetComponent<Canvas>();
            int rootOrder = canvas.sortingOrder;
            for (int i = 0; i < parent.childCount; i++)
            {
                UISortingManager.SetChildrenSortingOrder(parent.GetChild(i), canvas.sortingLayerName, rootOrder);
            }
        }

        private void OnGameObjectDestroy()
        {
            if (Application.isPlaying)
            {
                gameObject.RemoveDestroyEvent(OnGameObjectDestroy);

                if (UISortingManager.allComponents.Contains(this)) UISortingManager.allComponents.Remove(this);

                //UI关闭时，其他UI刷新一次
                RefreshOtherUI();
            }
        }

    }
}
